/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package ngmf.util;

import java.io.File;
import java.io.FileFilter;
import java.io.Serializable;
import java.util.Arrays;

public class WildcardFileFilter implements FileFilter, Serializable {

    private static final long serialVersionUID = 2998954975458664788L;
    /** The wildcards that will be used to match filenames. */
    private final String wildcards;
    /** Whether the comparison is case sensitive. */
    private final IOCase caseSensitivity;

    /**
     * Construct a new case-sensitive wildcard filter for a single wildcard.
     *
     * @param wildcard  the wildcard to match
     * @throws IllegalArgumentException if the pattern is null
     */
    public WildcardFileFilter(String wildcard) {
        this(wildcard, null);
    }

    /**
     * Construct a new wildcard filter for a single wildcard specifying case-sensitivity.
     *
     * @param wildcard  the wildcard to match, not null
     * @param caseSensitivity  how to handle case sensitivity, null means case-sensitive
     * @throws IllegalArgumentException if the pattern is null
     */
    public WildcardFileFilter(String wildcard, IOCase caseSensitivity) {
        if (wildcard == null) {
            throw new IllegalArgumentException("The wildcard must not be null");
        }
        this.wildcards = wildcard;
        this.caseSensitivity = (caseSensitivity == null ? IOCase.SENSITIVE : caseSensitivity);
    }

    /**
     * Checks to see if the filename matches one of the wildcards.
     *
     * @param file  the file to check
     * @return true if the filename matches one of the wildcards
     */
    @Override
    public boolean accept(File file) {
        String name = file.getName();
        if (FilenameUtils.wildcardMatch(name, wildcards, caseSensitivity)) {
            return true;
        }
        return false;
    }

    public static void main(String[] args) {
        File f = new File("c:/tmp");
        File[] fi = f.listFiles(new WildcardFileFilter("hey.groovy"));
        System.out.println(Arrays.toString(fi));
    }
}
